package com.glory.brepda.activity.lanjian;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.LotAndPackagingfileEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.entity.response.lotHisAndNum;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.Date;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class SfcBDStepCheckActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.flBeginTimeList)
    FrameLayout flBeginTimeList;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.ivBeginTimeArrow)
    ImageView ivBeginTimeArrow;

    @BindView(R.id.EQP)
    FreeUI_ClearEditText eqp;
    @BindView(R.id.LotId)
    FreeUI_ClearEditText LotId;
    @BindView(R.id.productModule)
    FreeUI_ClearEditText productModule;
    @BindView(R.id.cust)
    FreeUI_ClearEditText cust;
    @BindView(R.id.mainQty)
    FreeUI_ClearEditText mainQty;
    @BindView(R.id.boxQty)
    FreeUI_ClearEditText boxQty;
    @BindView(R.id.checkMan)
    FreeUI_ClearEditText checkMan;
    @BindView(R.id.gd_pass)
    RadioButton gd_pass;
    @BindView(R.id.gd_ng)
    RadioButton gd_ng;
    @BindView(R.id.gt_pass)
    RadioButton gt_pass;
    @BindView(R.id.gt_ng)
    RadioButton gt_ng;
    @BindView(R.id.bq_pass)
    RadioButton bq_pass;
    @BindView(R.id.bq_ng)
    RadioButton bq_ng;
    @BindView(R.id.qt_pass)
    RadioButton qt_pass;
    @BindView(R.id.qt_ng)
    RadioButton qt_ng;
    @BindView(R.id.error)
    FreeUI_ClearEditText error;
    @BindView(R.id.otherMainQty)
    FreeUI_ClearEditText otherMainQty;
    @BindView(R.id.otherLotId)
    FreeUI_ClearEditText otherLotId;
    @BindView(R.id.okMan)
    FreeUI_ClearEditText okMan;
    @BindView(R.id.BeiZu)
    FreeUI_ClearEditText BeiZu;

    @BindView(R.id.showError)
    LinearLayout showError;

    private String beginDate;
    private CustomDatePicker mDatePicker;
    private lotHisAndNum entity;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_sfc_bdstep_check;
    }

    @Override
    protected void initView() {

        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        initDatePicker();

        beginDate = FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", 0);
        tvBeginTime.setText(beginDate);

        initEdit(LotId, sa -> {
            //获取lot信息
            FreeUI_EntityCallBack<BaseResponseBean<lotHisAndNum>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<lotHisAndNum>>
                    (new TypeToken<BaseResponseBean<lotHisAndNum>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<lotHisAndNum>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        entity = response.body().getResponse().getBody();
                        inputvalue(entity);
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<lotHisAndNum>> response) {
                    super.onError(response);
                    loadError(response.getException(), "失败");
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("LOT_ID", getText(LotId));
            map.addProperty("ACTIVE", "PDA_BD_QUERY");
            NetUtils.requestPostNet("IF.PDA_BD_STEP_CHECK", "Common", getApplication(), map, callBack);
        });

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.flBeginTimeList,R.id.tvBaseSubmit,R.id.gd_pass,R.id.gt_pass,R.id.bq_pass,R.id.qt_pass,R.id.gd_ng,R.id.gt_ng,R.id.bq_ng,R.id.qt_ng})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flBeginTimeList:
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.gd_pass:
            case R.id.gt_pass:
            case R.id.bq_pass:
            case R.id.qt_pass:
//                点了某项之后可能仍然存在异常，全部没有异常才隐藏
                if(gd_pass.isChecked() && gt_pass.isChecked() && bq_pass.isChecked() && qt_pass.isChecked()){
                    // 需要把异常信息清理
                    error.setText(null);
                    otherMainQty.setText(null);
                    otherLotId.setText(null);
                    okMan.setText(null);
                    showError.setVisibility(View.GONE);
                }

                break;
            case R.id.gd_ng:
            case R.id.gt_ng:
            case R.id.bq_ng:
            case R.id.qt_ng:
//                任意异常，均显示异常部分
                showError.setVisibility(View.VISIBLE);
                break;
            case R.id.tvBaseSubmit:
                submit();
                break;
        }
    }

    private void submit(){

//        检查数据是否存在异常或数据为空
        if(checkResponseInfos()){
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("成功", true);
                    ClearInfos();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "PDA_QUERY_LOT_PACKS");

            }
        };
        JsonObject map = new JsonObject();

//        map.addProperty("USER_NAME",Constant.CURRENT_USER);
        map.addProperty("SENT_DATE", tvBeginTime.getText().toString());
        map.addProperty("EQP", getText(eqp));
        map.addProperty("LOT_ID", getText(LotId));
        map.addProperty("PRODUCT_MODULE", getText(productModule));
        map.addProperty("CUST", getText(cust));
        map.addProperty("MAIN_QTY", getText(mainQty));
        map.addProperty("BOX_QTY", getText(boxQty));
        map.addProperty("CHECK_MAN", getText(checkMan));
        map.addProperty("GD_PASS",gd_pass.isChecked()?"Y":"N");
        map.addProperty("GT_PASS",gt_pass.isChecked()?"Y":"N");
        map.addProperty("BQ_PASS",bq_pass.isChecked()?"Y":"N");
        map.addProperty("QT_PASS",qt_pass.isChecked()?"Y":"N");

        map.addProperty("ERROR",getText(error));
        map.addProperty("OT_MAIN_QTY",getText(otherMainQty));
        map.addProperty("OT_LOT_ID",getText(otherLotId));
        map.addProperty("OK_MAN",getText(okMan));
        map.addProperty("BEI_ZU",getText(BeiZu));
        map.addProperty("ACTIVE","PDA_BD_SAVE");

        NetUtils.requestPostNet("IF.PDA_BD_STEP_CHECK", "Common", SfcBDStepCheckActivity.this, map, callBack);
    }

    private void ClearInfos(){
        eqp.setText(null);
        LotId.setText(null);
        productModule.setText(null);
        cust.setText(null);
        mainQty.setText(null);
        boxQty.setText(null);
        checkMan.setText(null);

        error.setText(null);
        otherMainQty.setText(null);
        LotId.setText(null);
        okMan.setText(null);
        BeiZu.setText(null);
        otherLotId.setText(null);

//        gd_pass.setChecked(false);
//        gt_pass.setChecked(false);
//        bq_pass.setChecked(false);
//        qt_pass.setChecked(false);
//
//        gd_ng.setChecked(false);
//        gt_ng.setChecked(false);
//        bq_ng.setChecked(false);
//        qt_ng.setChecked(false);
    }

    private boolean checkResponseInfos(){

        boolean isOk = false;

        // 1, 检查非空项
        // 2, 检查单选按钮项。必须存在4项被选中，否则不能提交
        int n = 0;
        if(gd_pass.isChecked()){
            n++;
        }
        if(gt_pass.isChecked()){
            n++;
        }
        if(bq_pass.isChecked()){
            n++;
        }
        if(qt_pass.isChecked()){
            n++;
        }
        if(gd_ng.isChecked()){
            n++;
        }
        if(gt_ng.isChecked()){
            n++;
        }
        if(bq_ng.isChecked()){
            n++;
        }
        if(qt_ng.isChecked()){
            n++;
        }
        if(StringUtils.isEmpty(getText(eqp)) || StringUtils.isEmpty(getText(LotId)) ||
                StringUtils.isEmpty(getText(boxQty)) || StringUtils.isEmpty(getText(checkMan)) || n<4 ){
            showToast("请完善数据再提交",false);
            isOk = true;
            return  isOk;
        }

        Pattern pattern = Pattern.compile("^\\d+$");
        // 3, 勾选异常项，判断异常内容不为空,判断补料数量，确认人必须纯数字
        if(showError.getVisibility()==View.VISIBLE){
            if(StringUtils.isEmpty(getText(error)) || StringUtils.isEmpty(getText(otherMainQty)) ||
                    StringUtils.isEmpty(getText(otherLotId)) || StringUtils.isEmpty(getText(okMan))){
                showToast("请完善数据再提交",false);
                isOk = true;
                return  isOk;
            }

            if(!pattern.matcher(getText(otherMainQty)).matches() || !pattern.matcher(getText(okMan)).matches()){
                showToast("请确认输入是否存在异常字符",false);
                isOk = true;
                return  isOk;
            }

        }
        // 4，判断盒数,检验员必须纯数字
        if(!pattern.matcher(getText(boxQty)).matches() || !pattern.matcher(getText(checkMan)).matches()) {
            showToast("请确认输入是否存在异常字符", false);
            isOk = true;
            return  isOk;
        }
        // 5, zhi丹 要求 检验员跟确认人不能是同一个人
        if(showError.getVisibility()==View.VISIBLE){
            if(getText(checkMan).equals(getText(okMan))){
                showToast("祉丹：检验人跟确认人不能相同!", false);
                isOk = true;
                return  isOk;
            }
        }
        return  isOk;

    }

    private void inputvalue(lotHisAndNum entity){
        productModule.setText(entity.getLOTHIS().getUDF().getProductModel());
        cust.setText(entity.getLOTHIS().getCustomerCode());
        mainQty.setText(entity.getLOTHIS().getMainQty());
        eqp.setText(entity.getLOTHIS().getEquipmentId());
        boxQty.setText(entity.getBoxNum());
        // 盒数 = 批次数 / 盒基数 向上取整 (zhi丹要求操作工手动输入)
//        int BOX_NUM = (int)  Math.ceil(Integer.parseInt(entity.getLOT().getMAINQTY()) * 1.0 / Integer.parseInt(entity.getPACKS().getBoxNum()));
//        boxQty.setText(BOX_NUM);
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            beginDate = FreeApi_DateUtils.long2Str(timestamp, false);
            tvBeginTime.setText(beginDate);

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }
}